import json
import os
from conf import settings


# 创建路径
def creat_path(tag, path):
    '''
    :param tag: 项目类型，信息，流水，日志
    :param path: 文件名
    :return: 拼接好的绝对路径
    '''
    # 信息的绝对路径
    if tag == 'info':
        path = os.path.join(settings.USER_INFO_DIR, path)
    # 日志的绝对路径
    elif tag == 'log':
        path = os.path.join(settings.USER_LOG_DIR, path)
    elif tag == 'product':
        path = os.path.join(settings.PRODUCT_DIR, path)
    return path


# 读取信息
def read_data(tag, path, mode='r', encoding='utf8'):
    try:
        # 补充路径
        path = creat_path(tag, path)
        if tag == 'log':  # 后缀是log的文件
            with open(path, mode=mode, encoding=encoding) as fp:
                data = fp.read()
        else:  # 其他情况，也就是json文件
            with open(path, mode=mode, encoding=encoding) as fp:
                data = json.load(fp)
        return True, data
    except Exception as e:
        return False, f"读取信息时发生了一些错误!错误信息:{e}"


# 写入信息
def save_data(tag, path, data, mode='w', encoding='utf8'):
    try:
        path = creat_path(tag, path)
        with open(path, mode=mode, encoding=encoding) as fp:
            json.dump(data, fp, ensure_ascii=False)
            fp.flush()
        return True, '保存成功了'
    except Exception as e:
        return False, f"保存信息时发生了一些错误!错误信息:{e}"
